/**
 * 前端权限诊断工具
 * 用于深度诊断前端权限问题
 */

export class PermissionDiagnostic {
  /**
   * 诊断localStorage中的用户信息
   */
  static diagnoseLocalStorage() {
    const diagnostic = {
      timestamp: Date.now(),
      localStorageAvailable: typeof Storage !== 'undefined',
      items: {}
    }

    try {
      // 检查token
      const token = localStorage.getItem('token')
      diagnostic.items.token = {
        exists: !!token,
        value: token ? `${token.substring(0, 20)}...` : null,
        length: token ? token.length : 0,
        format: token ? this.validateTokenFormat(token) : null
      }

      // 解析token payload
      if (token) {
        try {
          const payload = this.parseTokenPayload(token)
          diagnostic.items.tokenPayload = payload
        } catch (error) {
          diagnostic.items.tokenPayload = {
            error: error.message
          }
        }
      }

      // 检查user_info
      const userInfoStr = localStorage.getItem('user_info')
      diagnostic.items.user_info = {
        exists: !!userInfoStr,
        value: userInfoStr,
        parsed: null,
        parseError: null
      }

      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          diagnostic.items.user_info.parsed = userInfo
          diagnostic.items.user_info.validation = this.validateUserInfo(userInfo)
        } catch (error) {
          diagnostic.items.user_info.parseError = error.message
        }
      }

      // 检查auth store数据
      const authStr = localStorage.getItem('auth')
      if (authStr) {
        try {
          diagnostic.items.auth = JSON.parse(authStr)
        } catch (error) {
          diagnostic.items.auth = { parseError: error.message }
        }
      }

    } catch (error) {
      diagnostic.error = error.message
    }

    return diagnostic
  }

  /**
   * 验证token格式
   */
  static validateTokenFormat(token) {
    if (!token) return { valid: false, error: 'Token为空' }

    const parts = token.split('.')
    if (parts.length !== 3) {
      return { valid: false, error: `Token格式错误: 应该有3部分，实际有${parts.length}部分` }
    }

    return { valid: true }
  }

  /**
   * 解析token payload
   */
  static parseTokenPayload(token) {
    const parts = token.split('.')
    if (parts.length !== 3) {
      throw new Error('Token格式错误')
    }

    try {
      const payload = JSON.parse(atob(parts[1]))
      const now = Math.floor(Date.now() / 1000)

      return {
        userId: payload.userId,
        username: payload.sub || payload.username,
        role: payload.role,
        issuedAt: payload.iat,
        expiresAt: payload.exp,
        issuedAtDate: payload.iat ? new Date(payload.iat * 1000).toLocaleString() : null,
        expiresAtDate: payload.exp ? new Date(payload.exp * 1000).toLocaleString() : null,
        isExpired: payload.exp ? payload.exp < now : null,
        remainingTime: payload.exp ? payload.exp - now : null,
        remainingTimeFormatted: payload.exp ? this.formatRemainingTime(payload.exp - now) : null
      }
    } catch (error) {
      throw new Error(`解析token payload失败: ${error.message}`)
    }
  }

  /**
   * 格式化剩余时间
   */
  static formatRemainingTime(seconds) {
    if (seconds < 0) return '已过期'
    if (seconds < 60) return `${seconds}秒`
    if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时`
    return `${Math.floor(seconds / 86400)}天`
  }

  /**
   * 验证用户信息
   */
  static validateUserInfo(userInfo) {
    const validation = {
      valid: true,
      errors: [],
      warnings: []
    }

    // 必填字段检查
    const requiredFields = ['id', 'username', 'role']
    for (const field of requiredFields) {
      if (!userInfo[field]) {
        validation.valid = false
        validation.errors.push(`缺少必填字段: ${field}`)
      }
    }

    // 字段类型检查
    if (userInfo.id && typeof userInfo.id !== 'number') {
      validation.warnings.push('id字段应该是数字类型')
    }

    // 角色格式检查
    if (userInfo.role) {
      const validRoles = ['admin', 'agent', 'customer', 'supervisor', 'readonly']
      const roleLower = userInfo.role.toLowerCase()
      if (!validRoles.includes(roleLower)) {
        validation.errors.push(`无效的角色: ${userInfo.role}`)
      }

      if (userInfo.role !== roleLower) {
        validation.warnings.push(`角色应该使用小写形式，当前: ${userInfo.role}`)
      }
    }

    return validation
  }

  /**
   * 诊断API请求头
   */
  static diagnoseRequestHeaders() {
    const token = localStorage.getItem('token')
    
    const diagnostic = {
      token: {
        exists: !!token,
        format: token ? `Bearer ${token.substring(0, 20)}...` : null
      },
      headers: {}
    }

    if (token) {
      diagnostic.headers = {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    }

    return diagnostic
  }

  /**
   * 诊断权限匹配
   */
  static diagnosePermissionMatch(userRole, requiredRoles) {
    const diagnostic = {
      userRole: userRole,
      userRoleLowerCase: userRole ? userRole.toLowerCase() : null,
      requiredRoles: requiredRoles,
      requiredRolesLowerCase: requiredRoles ? requiredRoles.map(r => r.toLowerCase()) : [],
      matches: false,
      matchDetails: []
    }

    if (!userRole) {
      diagnostic.error = '用户角色为空'
      return diagnostic
    }

    if (!requiredRoles || requiredRoles.length === 0) {
      diagnostic.error = '要求的角色列表为空'
      return diagnostic
    }

    const userRoleLower = userRole.toLowerCase()
    const requiredRolesLower = requiredRoles.map(r => r.toLowerCase())

    diagnostic.matches = requiredRolesLower.includes(userRoleLower)

    // 详细匹配过程
    diagnostic.matchDetails = requiredRolesLower.map(reqRole => ({
      requiredRole: reqRole,
      matches: reqRole === userRoleLower,
      comparison: `'${reqRole}' == '${userRoleLower}' ? ${reqRole === userRoleLower}`
    }))

    return diagnostic
  }

  /**
   * 打印诊断报告到控制台
   */
  static printDiagnosticReport() {
    console.log('%c╔════════════════════════════════════════════════════════════════', 'color: #2196F3; font-weight: bold')
    console.log('%c║ 🔍 前端权限诊断报告', 'color: #2196F3; font-weight: bold')
    console.log('%c╠════════════════════════════════════════════════════════════════', 'color: #2196F3; font-weight: bold')

    // LocalStorage诊断
    const lsDiagnostic = this.diagnoseLocalStorage()
    console.log('%c║ LocalStorage诊断:', 'color: #2196F3')
    console.log('%c║   - Token存在:', lsDiagnostic.items.token?.exists ? '✅ 是' : '❌ 否', 'color: ' + (lsDiagnostic.items.token?.exists ? '#4CAF50' : '#F44336'))
    
    if (lsDiagnostic.items.token?.exists) {
      console.log('%c║   - Token长度:', lsDiagnostic.items.token.length, 'color: #666')
      console.log('%c║   - Token格式:', lsDiagnostic.items.token.format?.valid ? '✅ 有效' : '❌ 无效', 'color: ' + (lsDiagnostic.items.token.format?.valid ? '#4CAF50' : '#F44336'))
    }

    if (lsDiagnostic.items.tokenPayload) {
      console.log('%c╠════════════════════════════════════════════════════════════════', 'color: #2196F3; font-weight: bold')
      console.log('%c║ Token Payload:', 'color: #2196F3')
      console.log('%c║   - 用户ID:', lsDiagnostic.items.tokenPayload.userId, 'color: #666')
      console.log('%c║   - 用户名:', lsDiagnostic.items.tokenPayload.username, 'color: #666')
      console.log('%c║   - 角色:', lsDiagnostic.items.tokenPayload.role, 'color: #666')
      console.log('%c║   - 发行时间:', lsDiagnostic.items.tokenPayload.issuedAtDate, 'color: #666')
      console.log('%c║   - 过期时间:', lsDiagnostic.items.tokenPayload.expiresAtDate, 'color: #666')
      console.log('%c║   - 是否过期:', lsDiagnostic.items.tokenPayload.isExpired ? '❌ 是' : '✅ 否', 'color: ' + (lsDiagnostic.items.tokenPayload.isExpired ? '#F44336' : '#4CAF50'))
      console.log('%c║   - 剩余时间:', lsDiagnostic.items.tokenPayload.remainingTimeFormatted, 'color: #666')
    }

    console.log('%c╠════════════════════════════════════════════════════════════════', 'color: #2196F3; font-weight: bold')
    console.log('%c║ User Info:', 'color: #2196F3')
    console.log('%c║   - 存在:', lsDiagnostic.items.user_info?.exists ? '✅ 是' : '❌ 否', 'color: ' + (lsDiagnostic.items.user_info?.exists ? '#4CAF50' : '#F44336'))

    if (lsDiagnostic.items.user_info?.parsed) {
      const userInfo = lsDiagnostic.items.user_info.parsed
      console.log('%c║   - ID:', userInfo.id, 'color: #666')
      console.log('%c║   - 用户名:', userInfo.username, 'color: #666')
      console.log('%c║   - 角色:', userInfo.role, 'color: #666')
      console.log('%c║   - 邮箱:', userInfo.email, 'color: #666')

      const validation = lsDiagnostic.items.user_info.validation
      if (validation) {
        console.log('%c║   - 验证结果:', validation.valid ? '✅ 通过' : '❌ 失败', 'color: ' + (validation.valid ? '#4CAF50' : '#F44336'))
        if (validation.errors.length > 0) {
          console.log('%c║   - 错误:', 'color: #F44336')
          validation.errors.forEach(err => console.log('%c║     * ' + err, 'color: #F44336'))
        }
        if (validation.warnings.length > 0) {
          console.log('%c║   - 警告:', 'color: #FF9800')
          validation.warnings.forEach(warn => console.log('%c║     * ' + warn, 'color: #FF9800'))
        }
      }
    }

    // 请求头诊断
    console.log('%c╠════════════════════════════════════════════════════════════════', 'color: #2196F3; font-weight: bold')
    const headersDiagnostic = this.diagnoseRequestHeaders()
    console.log('%c║ API请求头:', 'color: #2196F3')
    console.log('%c║   - Authorization:', headersDiagnostic.headers.Authorization ? '✅ 已设置' : '❌ 未设置', 'color: ' + (headersDiagnostic.headers.Authorization ? '#4CAF50' : '#F44336'))
    if (headersDiagnostic.headers.Authorization) {
      console.log('%c║   - 格式:', headersDiagnostic.token.format, 'color: #666')
    }

    console.log('%c╚════════════════════════════════════════════════════════════════', 'color: #2196F3; font-weight: bold')

    return lsDiagnostic
  }

  /**
   * 诊断并修复常见问题
   */
  static diagnoseAndFix() {
    console.log('%c🔧 开始诊断并修复权限问题...', 'color: #2196F3; font-weight: bold')

    const diagnostic = this.printDiagnosticReport()
    const fixes = []

    // 检查token是否过期
    if (diagnostic.items.tokenPayload?.isExpired) {
      fixes.push({
        issue: 'Token已过期',
        action: '需要重新登录',
        fix: () => {
          localStorage.removeItem('token')
          localStorage.removeItem('user_info')
          console.log('%c✅ 已清除过期的token和user_info', 'color: #4CAF50')
          window.location.href = '/login'
        }
      })
    }

    // 检查user_info是否有效
    if (!diagnostic.items.user_info?.exists || !diagnostic.items.user_info?.parsed) {
      fixes.push({
        issue: 'User info缺失或无效',
        action: '需要重新登录',
        fix: () => {
          localStorage.removeItem('token')
          localStorage.removeItem('user_info')
          console.log('%c✅ 已清除无效的认证信息', 'color: #4CAF50')
          window.location.href = '/login'
        }
      })
    }

    // 检查必填字段
    if (diagnostic.items.user_info?.validation && !diagnostic.items.user_info.validation.valid) {
      fixes.push({
        issue: 'User info字段不完整',
        action: '需要重新登录',
        fix: () => {
          localStorage.removeItem('token')
          localStorage.removeItem('user_info')
          console.log('%c✅ 已清除不完整的用户信息', 'color: #4CAF50')
          window.location.href = '/login'
        }
      })
    }

    if (fixes.length > 0) {
      console.log('%c📋 发现问题:', 'color: #FF9800; font-weight: bold')
      fixes.forEach((fix, index) => {
        console.log(`%c  ${index + 1}. ${fix.issue} - ${fix.action}`, 'color: #FF9800')
      })

      // 自动执行第一个修复
      console.log('%c🔧 自动执行修复...', 'color: #2196F3')
      if (fixes[0].fix) {
        fixes[0].fix()
      }
    } else {
      console.log('%c✅ 未发现问题，权限配置正常', 'color: #4CAF50; font-weight: bold')
    }

    return { diagnostic, fixes }
  }
}

// 在控制台中可以使用
window.PermissionDiagnostic = PermissionDiagnostic

// 添加快捷命令
window.diagPermission = () => PermissionDiagnostic.printDiagnosticReport()
window.fixPermission = () => PermissionDiagnostic.diagnoseAndFix()

export default PermissionDiagnostic

